<?php
/**
 * Created by PhpStorm.
 * User: Frings
 * Date: 2018/2/12
 * Time: 23:53
 */

namespace app\models;


use app\librarys\Tools;

class AdExt extends db\Ad
{


    public static function getSwiperAdCount($mini_program, $e_shop_id, $ad_category_id, $name = '')
    {
        return db\Ad::find()
            ->where(['is_deleted' => 0])
            ->andWhere(['mini_program_id' => $mini_program])
            ->andWhere(['e_shop_id' => $e_shop_id])
            ->andWhere(['ad_category_id' => $ad_category_id])
            ->andFilterWhere(['like', 'name', $name])
            ->count();
    }

    public static function getSwiperAdList($page = 0, $pageSize = 20,$mini_program, $e_shop_id, $ad_category_id, $name = '')
    {
        if ($page <= 0) $page = 0;
        $start = $page * $pageSize;

        $items = db\Ad::find()
            ->where(['is_deleted' => 0])
            ->andWhere(['mini_program_id' => $mini_program])
            ->andWhere(['e_shop_id' => $e_shop_id])
            ->andWhere(['ad_category_id' => $ad_category_id])
            ->andFilterWhere(['like', 'name', $name])
            ->orderBy('create_datetime desc')
            ->limit($pageSize)
            ->offset($start)
            ->all();
        return $items;
    }

    public static function getAdById($id)
    {
        $item = db\Ad::find()
            ->where(['id' => $id])
            ->one();
        return $item;
    }

    public static function saveAd($id,$e_shop_id,$name,$image_id,$link_url,$description,$is_shown,$ad_category_id,$sort,$mini_program_id,$is_enabled)
    {
        $item = self::getAdById($id);
        if(!$item){
            $item = new db\Ad();
            $item->id = Tools::db_uuid();
            $item->is_deleted = 0;
        }

        $item->e_shop_id = $e_shop_id;
        $item->name = $name;
        $item->image_id = $image_id;
        $item->link_url = $link_url;
        $item->description = $description;
        $item->is_shown = $is_shown;
        $item->ad_category_id = $ad_category_id;
        $item->sort = $sort;
        $item->mini_program_id = $mini_program_id;
        $item->is_enabled = $is_enabled;

        $result = $item->save();
        return $result;
    }

    public static function deleteAd($id)
    {
        $item = self::getAdById($id);
        $item->is_deleted = 1;

        $result = $item->save();
        return $result;
    }
}